﻿/**
 * @description 站点管理统一入口文件
 * @author changyin@lzlu.com			
 * @version 0.1
 * @requires seajs,jquery
 */

define(function(require, exports, module) {
	var $ = require('jquery');
	//tan切换
	$(function(){
		var tnav = $("#tnav>ul>li"),
			tcontant = $("#tcontent>div.gitem");
			
		if(tnav.length!=tcontant.length)return;
		
		$.each(tnav,function(index){
			$(this).bind("mouseover",function(){
				$(tcontant).hide();
				$(tnav).removeClass("active");
				$(this).addClass("active");
				$(tcontant[index]).show();
			});
		})
	});

    /**
     * timer管理器
     */
    var timeManager = (function(){
	var CHECKER_INTERVAL = 300000; //校准间隔时间
        /**
         * 倒计时
         */
        var Timer = function(config){
            
            /**
             * 默认配置
             */
            var defConfig = {
                //结束时间，毫秒时间戳
                timeEnd: 0,
                //当前时间，毫秒时间戳
                timeCurrent: 0,
                //直接定义剩余时长，毫秒
                timeLeft : 0,
                //容器
                container: null,
                //显示样式：0 1
                style: 0,
                //时间结束回调
                callback: null
            };
            
			$.each(config || {},function(key,value){
				defConfig[key] = value;
			})
			this.config = defConfig;
			
			
            
            /**
             * 剩余时间
             */
            this.leftTime = 0;
            
            /**
             * 容器
             */
            this.container = null;
            
            /**
             * interval handler
             */
            this.timeHandler = null;
            
            /**
             * 校准偏移
             */
            this.timeOffset = 0;
            

			
            /**
             * 初始化
             */
            this.init();
			

            
         };
         
         Timer.prototype = {
             
             /**
              * 初始化
              */
             init: function(){
                 
                 //检查
                 if(!this.valider()) {
                     return;
                 }
                 
                 //显示方式
                 this.display = (this.config.style == 1) ? this.display1 : this.display0;
                 
                 //初始状态
                 var timeObj = this.divider();
                 
                 this.display(timeObj);
                 
                 //倒计时
                 this.counter();
                 this.dCounter();
                 
             },
             /**
              * 倒计时
              */
             counter: function(){
                 var self = this;
                 this.timeHandler = setInterval(function(){
                     
                    self.leftTime--;
                     
                    if (self.leftTime < 0) {
                        self.onOver(); //结束倒计时执行
                        return;
                    }
                    
                    var timeObj = self.divider();
                    
                    self.display(timeObj);
                    
                 }, 1000);
             },
             
             /**
              * 分秒倒计时
              */
             dCounter: function(){
                 if(!this.timeBox.ds) {
                     return;
                 }
                 
                 var dsec = 9, self = this;
                 this.dTimeHandler = setInterval(function(){
    
                    if (dsec <0 ) {
                        dsec = 9;
                    }
                    
                    self.timeBox.ds.innerHTML = '.'+dsec;
                    
                    dsec--;
                    
                }, 100);
                 
             },
             
             /**
              * 检查
              */
             valider: function(){
                 
                 //容器必须有
                 this.container = $(this.config.container);
                 if(!this.container) {
                     return;
                 };
                 
                 //结束时间必须有
                 if (!this.config.timeLeft && !this.config.timeEnd) {
                     return;
                 }
                 
                 //开始时间没有，取客户端时间
                 if (!this.config.timeCurrent) {
                     var clientTime = new Date(); //否则使用客户端时间
                     this.config.timeCurrent = clientTime.getTime();
                 }
                 
                 //剩余时间
                 this.leftTime = this.config.timeLeft || (this.config.timeEnd - this.config.timeCurrent);
                 
                 this.leftTime = parseInt(this.leftTime / 1000);
                 
                 if (this.leftTime <= 0) {
                     return;
                 }
 
                 if(this.config.style == 1) {
                     //dom处理
                     var items = $(this.container).find("span");
                     this.timeBox = {
                         h1 : items[0],
                         h2 : items[1],
                         m1 : items[3],
                         m2 : items[4],
                         s1 : items[6],
                         s2 : items[7]
                     }
                 }
                 else{
                     //dom处理
                     var items = $(this.container).find("i");
                     this.timeBox = {
                         h : items[0],
                         m : items[1],
                         s : items[2],
                         ds: items[3]
                     }
                 }
				 
                 
                 return true;
                 
             },
             
             /**
              * 计算时间
              */
             divider: function(){
                 
                 //this.leftTime
                 
                 var hours, minutes, seconds;
                 
                 hours = Math.floor(this.leftTime / 3600);
                 minutes = Math.floor(this.leftTime / 60 % 60);
                 seconds = this.leftTime % 60;

                 return {
                     'hours':hours,
                     'minutes':minutes,
                     'seconds':seconds
                 };
                 
                 
             },
             display:function(){
                 
             },
             /**
              * 显示0
              */
             display0: function(timeObj){
                 this.timeBox.h.innerHTML = timeObj.hours;
                 this.timeBox.m.innerHTML = timeObj.minutes;
                 this.timeBox.s.innerHTML = timeObj.seconds;
             },
             /**
             * 显示效果1
             */
            display1 : function(timeObj){

                //拆分时间
                var hour = this.divStr(timeObj.hours),
                    minute = this.divStr(timeObj.minutes),
                    second = this.divStr(timeObj.seconds);
                
                this.timeBox.h1.className = 't' + hour.charAt(0);
                this.timeBox.h2.className = 't' + hour.charAt(1);
                this.timeBox.m1.className = 't' + minute.charAt(0);
                this.timeBox.m2.className = 't' + minute.charAt(1);
                this.timeBox.s1.className = 't' + second.charAt(0);
                this.timeBox.s2.className = 't' + second.charAt(1);
            },
            divStr: function(str){
                var tmp = '0' + str;
                    tmp = tmp.substr((tmp.length - 2), 2);
                return tmp;
            },
             
             /**
              * 结束倒计时处理
              */
             onOver: function(){
                 
                //清除定时器
                try {
                    clearInterval(this.timeHandler);
                    if(this.dTimeHandler) clearInterval(this.dTimeHandler);
                    //分秒置空
                    this.timeBox.h.innerHTML = '0';
                    this.timeBox.m.innerHTML = '0';
                    this.timeBox.s.innerHTML = '0';
                    this.timeBox.ds.innerHTML = '.0';
                } 
                catch (e) {
                    
                }
                
                //回调函数
                var callback = this.config.callback;
                if(callback && this.leftTime <= 0) {
                    callback && callback.call(this, this.container);
                }
                else{
                    this.leftTime = 0;
                }
    
             },
             
             /**
              * 外部唤醒校准
              * 并返回秒表状态供判断
              * off = st1 + lt1
              * lt2 = off - st2
              */
             calibrate: function(serverTime){

                if (this.leftTime <= 0) {
                    return false;
                }
                 
                if(!this.timeOffset) {
                    this.timeOffset = serverTime + this.leftTime;
                }
                else{
                    this.leftTime = this.timeOffset - serverTime;
                }
                return true;
             }
             
         };
         
         
         /**
          * 检查器
          */
         
         var checker = {
             
             /**
              * checker
              */
             checkerRunner: null,
             
             /**
              * checker运行状态
              */
             checkerOn:0,
             
             /**
              * 服务器时间
              */
             serverDate:0,
             
             /**
              * 初始化checker
              */
             init: function(){
                 if(this.checkerOn) return;
                 //定时校准服务器时间
                 var self = this;
                 this.checkerRunner = setInterval(function(){
                     
                    var xhr = self.getXMLHttpRequest(), serverDate, serverTime;
                    xhr.onreadystatechange = function(){
                        if (xhr.readyState == 4) {
                            //取得响应头时间
                            serverDate = new Date(xhr.getResponseHeader('date'));
                            serverTime = Math.floor(serverDate.getTime() / 1000);
                            self.calibrater(serverTime);
                        }
                    };
                    xhr.open('HEAD', '/?'+Math.random());
                    xhr.send(null);
    
                 },CHECKER_INTERVAL);
                 
                 self.checkerOn = 1;
                 
             },
             
             getXMLHttpRequest: function(){
                try{
                   if(window.XMLHttpRequest){
                     return new XMLHttpRequest();
                   }
                   if(window.ActiveXObject){
                     return new ActiveXObject("MSXML2.XmlHttp");
                   }
                }catch(e){

                }   
              },
             
             /**
              * 校准器
              */
             calibrater: function(serverTime){
                 
                 if(this.serverDate == serverTime) {
                     return;
                 }

                 var needChecker = 0;
                 $.each(timers, function(index,timer){
                     needChecker = needChecker || (timer.leftTime > 0);
                     timer.calibrate(serverTime);
                 })
                 
                 this.serverDate = serverTime;

                 /**
                  * 所有秒表已结束：停止checker
                  */
                 if(!needChecker) {
                     this.clearChecker();
                 }
             },
             
             /**
              * 停止checker
              */
             clearChecker: function(){
                try {
                    clearInterval(this.checkerRunner);
                } 
                catch (e) {
                    
                }
                this.checkerOn = 0;
             }
         }
         /**
          * timer实例
          */
         var timers = [];

         return {
             /**
              * 外部初始化Timer接口
              */
             create: function(conf){
                 checker.init();
                 var aTimer = new Timer(conf);
                 timers.push(aTimer);
                 return aTimer;
             },
             /**
              * 销毁
              */
             remove: function(theTimer){
                 if($.inArray(theTimer, timers)) {
                     theTimer.onOver();
                 }
             }
         }
    })();
	$(".timer").each(function(){
		
		var timeEnd     = $(this).attr('data-targettime'),
			timeCurrent = $(this).attr('data-servertime');
		
		timeManager.create({
			timeEnd: timeEnd,
			timeCurrent: timeCurrent,
			timeLeft: 0,
			container: $(this),
			style: 'simple',
			callback: function(){
				//刷新页面
				window.location.reload();
			}
		});
	});
	//倒计时
	//new Ju.app.timer(
});

<!--定义JS函数,ID命名的noIDName前缀部分，totalNum同组TAB窗口总数-->
function setTab(noIDName,currentID,totalNum){
for(i=1;i<=totalNum;i++){
var menu=document.getElementById(noIDName+i);
<!--对应的内容的名字-->
var con=document.getElementById(noIDName+"Content"+i);
<!--放上去的时候的样式名字-->
menu.className=i==currentID?"currentHover"+noIDName:"";
//alert(currentID?"currentHover"+noIDName:"")
con.style.display=i==currentID?"block":"none";
}
}

function copyToClipBoard() {
	var txt = '';
	txt += '今日团购';
	txt += ":";
	txt += window.parent.location;
	if (window.clipboardData) {
		window.clipboardData.clearData();
		window.clipboardData.setData("Text", txt);
	} else if (navigator.userAgent.indexOf("Opera") != -1) {
		window.location = txt;
	} else if (window.netscape) {
		try {
			netscape.security.PrivilegeManager
					.enablePrivilege("UniversalXPConnect");
		} catch (e) {
			alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
			return;
		}
		var clip = Components.classes['@mozilla.org/widget/clipboard;1']
				.createInstance(Components.interfaces.nsIClipboard);
		if (!clip)
			return;
		var trans = Components.classes['@mozilla.org/widget/transferable;1']
				.createInstance(Components.interfaces.nsITransferable);
		if (!trans)
			return;
		trans.addDataFlavor('text/unicode');
		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;1"]
				.createInstance(Components.interfaces.nsISupportsString);
		var copytext = txt;
		str.data = copytext;
		trans.setTransferData("text/unicode", str, copytext.length * 2);
		var clipid = Components.interfaces.nsIClipboard;
		if (!clip)
			return false;
		clip.setData(trans, null, clipid.kGlobalClipboard);
		alert("复制成功！")
	}
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24465941-1']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();